package springboot.dao;

import springboot.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class RoleDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    public Role getRolesById(int id){
        String sql = "select * from role where id = ?";
        List<Role> roles = jdbcTemplate.query(sql, new RowMapper<Role>() {
            @Override
            public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
                Role role = new Role();
                role.setId(rs.getInt("id"));
                role.setRole(rs.getString("role"));
                role.setDescription(rs.getString("description"));
                role.setPermissions(permissionDao.getPermissionsByIds(rolePermissionDao.getPermissionByRoleId(id)));
                return role;
            }
        }, id);
        if (roles.size()>0){
            return roles.get(0);
        }else{
            return null;
        }
    }
}
